package com.allwees.support.api.compatible;

import com.allwees.core.common.util.http.RequestUtil;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;

public class ApiCondition implements RequestCondition<ApiCondition> {

    private ApiVersionCompator version;

    public ApiCondition(ApiVersionCompator version) {
        this.version = version;
    }

    @Override
    public ApiCondition combine(ApiCondition other) {
        return this.version.compareTo(other.version) >= 0 ? this : other;
    }

    @Override
    public ApiCondition getMatchingCondition(HttpServletRequest request) {
        String xapi = request.getHeader(RequestUtil.X_API_VERSION);
        ApiVersionCompator version = ApiVersionConverter.convert(xapi);
        if (version.compareTo(this.version) >= 0) {
            return this;
        }
        return null;
    }

    @Override
    public int compareTo(ApiCondition other, HttpServletRequest request) {
        return other.version.compareTo(this.version);
    }
}